package com.litt.saap.system.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.litt.core.common.Utility;
import com.litt.core.dao.page.IPageList;
import com.litt.core.dao.ql.PageParam;
import com.litt.core.exception.NotLoginException;
import com.litt.core.module.annotation.Func;
import com.litt.core.web.mvc.action.BaseController;
import com.litt.core.web.util.WebUtils;
import com.litt.saap.common.vo.LoginUserVo;
import com.litt.saap.core.common.SaapConstants;
import com.litt.saap.core.common.SaapConstants.RoleStatus;
import com.litt.saap.core.web.util.LoginUtils;
import com.litt.saap.crm.service.ICustomerService;
import com.litt.saap.system.biz.ITenantBizService;
import com.litt.saap.system.po.BizRole;
import com.litt.saap.system.po.BizRoleDataPermission;
import com.litt.saap.system.po.BizRoleMember;
import com.litt.saap.system.po.Role;
import com.litt.saap.system.po.UserInfo;
import com.litt.saap.system.service.IBizRoleService;
import com.litt.saap.system.service.IRoleService;
import com.litt.saap.system.service.ITenantMemberService;

/**
 * 
 * Roles controller.
 * <pre><b>Description：</b>
 *    Role and privilege Management
 * </pre>
 * 
 * @author <a href="mailto:littcai@hotmail.com">Bob.cai</a>
 * @since 2014-02-27
 * @version 1.0
 */
@Controller
public class BizRoleController extends BaseController
{
	private final static Logger logger = LoggerFactory.getLogger(BizRoleController.class);

	@Resource
	private IRoleService roleService;
	@Resource
	private IBizRoleService bizRoleService;
	@Resource
	private ITenantBizService tenantBizService;
	
	@Resource
	private ITenantMemberService tenantMemberService;
	
	@Resource
	private ICustomerService customerService;
	
	/**
	 * default page.
	 * 
	 * @param request the request
	 * @param respnose the respnose
	 * 
	 * @return ModelAndView
	 */	
	@Func(funcCode="query", moduleCode="tenant.bizRole", enableLog=false) 
	@RequestMapping 
	public ModelAndView index(WebRequest request, ModelMap modelMap) throws NotLoginException
	{	
		LoginUserVo loginUserVo = (LoginUserVo)super.getLoginVo();
		
		//get params from request		
		String name = request.getParameter("name");
				
		//package the params
		PageParam pageParam = WebUtils.getPageParam(request);
		pageParam.addCond("tenantId", loginUserVo.getTenantId());
		pageParam.addCond("name", name);	
		pageParam.addCond("isDeleted", false);	
		//Get page result
		IPageList pageList = bizRoleService.listPage(pageParam);		
		
		//return params to response
		modelMap.addAttribute("pageParam", pageParam);	
		modelMap.addAttribute("pageList", pageList);	
		
    return new ModelAndView("/system/bizRole/index");	
	
	} 	
	
	/**
	 * Add Page.
	 * 
	 * @return ModelAndView
	 */	
	@Func(funcCode="add", moduleCode="tenant.bizRole", enableLog=false)  
	@RequestMapping
	public ModelAndView add() 
	{   
		List<Map> nodeList = bizRoleService.findBizRolePermissionTree(LoginUtils.getTenantId(), null);
		
		return new ModelAndView("/system/bizRole/add").addObject("nodeList", nodeList);
    }
	
	/**
	 * Edit Page.
	 * 
	 * @param id 
	 * 
	 * @return ModelAndView
	 */
	@Func(funcCode="edit", moduleCode="tenant.bizRole", enableLog=false)  
	@RequestMapping 
	public ModelAndView edit(@RequestParam Integer id) 
	{ 
		BizRole bizRole = bizRoleService.load(id);
		List<Map> nodeList = bizRoleService.findBizRolePermissionTree(LoginUtils.getTenantId(), id);
        return new ModelAndView("/system/bizRole/edit").addObject("bizRole", bizRole).addObject("nodeList", nodeList);
    }
	
	@Func(funcCode="edit", moduleCode="tenant.bizRole", enableLog=false)  
	@RequestMapping 
	public ModelAndView editMember(WebRequest request, ModelMap modelMap) 
	{ 
		BizRole bizRole = bizRoleService.load(Integer.parseInt(request.getParameter("id")));
		
		LoginUserVo loginUserVo = (LoginUserVo)super.getLoginVo();
		
		//get params from request
		Map<String, Object> params = WebUtils.getParametersStartingWith(request, SaapConstants.DEFAULT_SEARCH_PREFIX);
			
		String searchField = Utility.trimNull(params.get("searchField"));
		Object searchValue = params.get("searchValue");
				
		//package the params
		PageParam pageParam = WebUtils.getPageParam(request);
		pageParam.addCond("tenantId", loginUserVo.getTenantId());
		pageParam.addCond(searchField, searchValue);	
		pageParam.addCond("isDeleted", false);	
		pageParam.setPageSize(500);
		//Get page result
		IPageList pageList = tenantMemberService.listPage(pageParam);		
		
		//return params to response
		modelMap.addAttribute("pageParam", pageParam);	
		modelMap.addAttribute("pageList", pageList);
		modelMap.addAttribute("bizRole", bizRole);
		
		List<Map> rsList = pageList.getRsList();
		List<BizRoleMember> memberList = bizRoleService.listBizRoleMember(bizRole.getTenantId(), bizRole.getId());
		Map<Integer, BizRoleMember> memberMap = new HashMap<Integer, BizRoleMember>();
		if(null != memberList){
			for(BizRoleMember member : memberList){
				memberMap.put(member.getUserId(), member);
			}
		}
		for(Map rs : rsList){
			UserInfo userInfo = (UserInfo)rs.get("userInfo");
			BizRoleMember member = memberMap.get(userInfo.getId());
			if(null != member){
				rs.put("checked", true);
			}
		}
		
        return new ModelAndView("/system/bizRole/editMember");
    }
	
	@Func(funcCode="edit",moduleCode="tenant.bizRole")
	@RequestMapping 
	public void updateMember(WebRequest request, ModelMap modelMap) throws Exception
	{	
		String[] roleMemberIds = request.getParameterValues("roleMemberIds");
		
		BizRole bizRole = bizRoleService.load(Utility.parseInt(request.getParameter("id")));
		BeanUtils.populate(bizRole, request.getParameterMap());
		bizRoleService.updateBizRoleMember(bizRole, roleMemberIds);
	}
	
	@Func(funcCode="edit", moduleCode="tenant.bizRole", enableLog=false)  
	@RequestMapping 
	public ModelAndView editDataPerm(WebRequest request, ModelMap modelMap) 
	{ 
		BizRole bizRole = bizRoleService.load(Integer.parseInt(request.getParameter("id")));
		
		LoginUserVo loginUserVo = (LoginUserVo)super.getLoginVo();
		
		//get params from request
		Map<String, Object> params = WebUtils.getParametersStartingWith(request, SaapConstants.DEFAULT_SEARCH_PREFIX);
			
		String searchField = Utility.trimNull(params.get("searchField"));
		Object searchValue = params.get("searchValue");
				
		//package the params
		PageParam pageParam = WebUtils.getPageParam(request);
		pageParam.addCond("tenantId", loginUserVo.getTenantId());
		pageParam.addCond(searchField, searchValue);	
		pageParam.addCond("isDeleted", false);	
		pageParam.setPageSize(500);
		//Get page result
		IPageList pageList = tenantMemberService.listPage(pageParam);		
		
		//return params to response
		modelMap.addAttribute("pageParam", pageParam);	
		modelMap.addAttribute("pageList", pageList);
		modelMap.addAttribute("bizRole", bizRole);
		
		List<Map> rsList = pageList.getRsList();
		List<BizRoleDataPermission> dpList = bizRoleService.listBizRoleDataPermission(bizRole.getTenantId(), bizRole.getId());
		Map<String, BizRoleDataPermission> dpMap = new HashMap<String, BizRoleDataPermission>();
		if(null != dpList){
			for(BizRoleDataPermission dp : dpList){
				dpMap.put(dp.getFieldValue() + "," + dp.getFieldName(), dp);
			}
		}
		for(Map rs : rsList){
			UserInfo userInfo = (UserInfo)rs.get("userInfo");
			BizRoleDataPermission dp = dpMap.get(String.valueOf(userInfo.getId()) + ",chargeBy");
			if(null != dp){
				rs.put("checked", true);
				rs.put("fieldName", dp.getFieldName());
			}
		}
		
		//从请求中获取查询条件		
		String code = request.getParameter("code");
		String name = request.getParameter("name");
				
		//封装到分页参数对象中
		PageParam pageParam2 = WebUtils.getPageParam(request);
		pageParam2.addCond("tenantId", loginUserVo.getTenantId());
		pageParam2.addCond("code", code);	
		pageParam2.addCond("name", name);
		pageParam2.setPageSize(500);
		pageParam2.addCond("isDeleted", false);	
		//分页查询
		IPageList pageList2 = customerService.listPage(pageParam);
		
		List<Map> rsList2 = pageList2.getRsList();
		for(Map rs : rsList2){
			int id = (Integer)rs.get("ID");
			BizRoleDataPermission dp = dpMap.get(String.valueOf(id) + ",customerId");
			if(null != dp){
				rs.put("checked", true);
				rs.put("fieldName", dp.getFieldName());
			}
		}
		
		modelMap.addAttribute("pageList2", pageList2);
		
        return new ModelAndView("/system/bizRole/editDataPerm");
    }
    
	@Func(funcCode="edit",moduleCode="tenant.bizRole")
	@RequestMapping 
	public void updateDataPerm(WebRequest request, ModelMap modelMap) throws Exception
	{	
		String data = request.getParameter("data");
		String fieldName = request.getParameter("fieldName");
		BizRole bizRole = bizRoleService.load(Utility.parseInt(request.getParameter("id")));
		BeanUtils.populate(bizRole, request.getParameterMap());
		bizRoleService.updateBizRoleDataPermission(bizRole, data, fieldName);
	}
	
	/**
	 * Show Page.
	 * 
	 * @param id 
	 * 
	 * @return ModelAndView
	 */
	@Func(funcCode="query", moduleCode="tenant.bizRole", enableLog=false)  
	@RequestMapping 
	public ModelAndView show(@RequestParam Integer id) 
	{ 
		Role role = roleService.load(id);		
        return new ModelAndView("/system/bizRole/show").addObject("role", role);
    }   
    
    /**
	 * Save.
	 * @param request 
	 * @param modelMap
	 * @throws Exception 
	 */
	@Func(funcCode="add",moduleCode="tenant.bizRole")
	@RequestMapping 
	public void save(WebRequest request, ModelMap modelMap) throws Exception
	{	
		String[] moduleCodes = request.getParameterValues("moduleCodes");
		String[] fields = request.getParameterValues("fields");
		
		BizRole bizRole = new BizRole();
		BeanUtils.populate(bizRole, request.getParameterMap());	
		bizRole.setTenantId(LoginUtils.getTenantId());
		bizRole.setStatus(RoleStatus.NORMAL);
		bizRoleService.save(bizRole, moduleCodes, fields);
	}
	
	/**
	 * Update.
	 * @param request 
	 * @param modelMap
	 * @throws Exception 
	 */
	@Func(funcCode="edit",moduleCode="tenant.bizRole")
	@RequestMapping 
	public void update(WebRequest request, ModelMap modelMap) throws Exception
	{
		String[] moduleCodes = request.getParameterValues("moduleCodes");
		String[] fields = request.getParameterValues("fields");
		
		BizRole bizRole = bizRoleService.load(Utility.parseInt(request.getParameter("id")));
		BeanUtils.populate(bizRole, request.getParameterMap());
		bizRoleService.update(bizRole, moduleCodes, fields);
	}
	
	/**
	 * Delete.
	 * @param id id
	 * @throws Exception 
	 */
	@Func(funcCode="delete",moduleCode="tenant.bizRole")
	@RequestMapping 
	public void delete(@RequestParam Integer id) throws Exception
	{
		bizRoleService.delete(id);
	}

	/**
	 * Delete Batch.
	 * @param id id
	 * @throws Exception 
	 */
	@Func(funcCode="delete",moduleCode="tenant.bizRole")
	@RequestMapping 
	public void deleteBatch(@RequestParam(value="ids[]") Integer[] ids) throws Exception
	{
		roleService.deleteBatch(ids);
	}
	
	/**
	 * Resume.
	 * @param id id
	 * @throws Exception 
	 */
	@Func(funcCode="resume",moduleCode="tenant.bizRole")
	@RequestMapping 
	public void resume(@RequestParam Integer id) throws Exception
	{
		bizRoleService.doResume(id);
	}

}
